package edu.ncut.vod.struts.action;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Random;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import edu.ncut.vod.commonbeans.ADBean;
import edu.ncut.vod.commonbeans.DBConnection;
import edu.ncut.vod.struts.action.base.BaseAction;
import edu.ncut.vod.struts.form.AdvertisementForm;

public class AdvertisementAction extends BaseAction {

    /*
     * public interface ServletConfig:A servlet configuration object used by a servlet container
     * used to pass information to a servlet during initialization. 
     */
    ServletConfig servletConfig;
    private ArrayList ids;//store all id of ads
    
    /**
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        //debug("action begins");
        AdvertisementForm advertisementForm = (AdvertisementForm) form;
        
        String style = advertisementForm.getStyle();
        String id = advertisementForm.getId();
        
        //debug("style:" + style);
        //debug("id:" + id);
        
        if (style == null) {//refresh request from client to refresh browser
            //debug("parameter is refresh");            
        }else // click request from client browser to count the amount of clicking corresponding picture
            if(style != null && style.equals("link")){ 
            //debug("parameter is link");
            updateClickRecord(request,advertisementForm);
        }
                
        refreshAD(request, response); // refresh the show of advertisement
        return mapping.findForward("goHome");
    }

    /**
     * Method updateClickRecord:add data into database to record the number of clicking ads
     * @param request
     */
    private void  updateClickRecord(HttpServletRequest request,AdvertisementForm advertisementForm){
        
        /**
         * public java.lang.String getRemoteUser():Returns the login of the user making this 
         * request, if the user has been authenticated, or null if the user has not been 
         * authenticated.
         */
        String IP=request.getRemoteAddr();        
        String currentID=advertisementForm.getId();
        //debug("IP:"+IP);
        //debug("currentID:"+currentID);
        
        if(currentID==null){
            return;
        }
        
        int cid=Integer.parseInt(currentID);
        int result;
        
        DBConnection db=new DBConnection();
        PreparedStatement preparedStmt; //An object that represents a precompiled SQL statement. 
       
        try {
            preparedStmt =db.getConnection().prepareStatement("insert into adclickinfo (adid,clientip,clicktime) values(?,?,now())");
            preparedStmt.setInt(1,cid);
            preparedStmt.setString(2,IP);
            result=preparedStmt.executeUpdate(); 
        } catch (SQLException e) {
            e.printStackTrace();
        }                     
    }
    
    /**
     * refresh the show of advertisement
     * @param request
     * @param response
     */
    public void refreshAD(HttpServletRequest request,
            HttpServletResponse response) {
        String imgPath = (String) request.getSession().getAttribute("IMG_PATH");
        if (imgPath == null) {
            /*
             * public java.lang.String getInitParameter(java.lang.String name):Returns a String 
             * containing the value of the named initialization parameter, or null if the 
             * parameter does not exist.
             */
            String ADDir = getServlet().getInitParameter("ADImgPath");//servletConfig.getInitParameter("config");
            //debug(ADDir);
            request.getSession().setAttribute("IMG_PATH", ADDir);
        }

        int i = getRandomADID();//get ID of advertisement on random
        //debug("i :"+i);
        ADBean adBean = new ADBean(i);
        request.setAttribute("adBean",adBean);
    }
    
    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    
    /**
     * method getRandomADID:get ID of advertisement on random
     * @return
     */
    public int getRandomADID(){
        if(getIds().isEmpty()){
            DBConnection db=new DBConnection();
            java.sql.Statement stmt;
            java.sql.ResultSet sqlRst;
            try{
                /*
                 * Statement createStatement(int resultSetType,int resultSetConcurrency):throws 
                 * SQLExceptionCreates a Statement object that will generate ResultSet objects 
                 * with the given type and concurrency.
                 * static final int TYPE_SCROLL_INSENSITIVE:The constant indicating the type for 
                 * a ResultSet object that is scrollable but generally not sensitive to changes 
                 * to the data that underlies the ResultSet. 
                 * static final int CONCUR_READ_ONLY:The constant indicating the concurrency mode
                 * for a ResultSet object that may NOT be updated.  
                 */
                stmt =db.getConnection().createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
                String sqlQuery="select adid from adinfo";
                sqlRst=stmt.executeQuery(sqlQuery);
                
                // get next record and add its id to ArrayList object 'ids'
                while (sqlRst.next()) { 
                    ids.add(sqlRst.getInt("adid"));                    
                }
                
            } catch(Exception e){
                e.toString();
            }
        }
        //select a number on random
        int max=ids.size();
        //debug("max:"+max);
        Random random=new Random();
        /*
         * public int nextInt(int n):Returns a pseudorandom, uniformly distributed int value between 
         * 0 (inclusive) and the specified value (exclusive), drawn from this random number 
         * generator's sequence.
         */
        int temp=random.nextInt(max);
        //debug("temp:"+temp);
        return temp;
    }

    /**
     * @return the ids
     */
    public ArrayList getIds() {
        if(null == ids){
            ids=new ArrayList();
        }
        return ids;
    }
    
    /**
     * @param ids the ids to set
     */
    public void setIds(ArrayList ids) {
        this.ids = ids;
    }
    
    /**
     * console input for the purpose of debugging code
     * @param msg
     */
    public void debug(String msg) {
        System.out.println(msg);
    }
    
}